package com.atguigu.flink.chapter11;

import com.atguigu.flink.chapter05.Source.WaterSensor;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;

/**
 * TODO
 *
 * @author cjp
 * @version 1.0
 * @date 2021/1/27 10:11
 */
public class Flink07_SQL_Demo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<WaterSensor> sensorDS = env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                new WaterSensor("sensor_1", 2000L, 20),
                new WaterSensor("sensor_2", 3000L, 30),
                new WaterSensor("sensor_1", 4000L, 40),
                new WaterSensor("sensor_1", 5000L, 50),
                new WaterSensor("sensor_2", 6000L, 60));

        // 创建 表的执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        // TODO 使用 SQL 对动态表 进行 连续查询(  字段名用表达式： $("字段名")   )
        // 注册表名:
        // 方式一：从 table对象，注册表名
//        Table sensorTable = tableEnv.fromDataStream(sensorDS);
//        tableEnv.createTemporaryView("inputTable", sensorTable);

        // 方式二：直接从 流，转换成表，并注册表名(没有 Table的对象)
        tableEnv.createTemporaryView("inputTable", sensorDS);
        // 这种方式，如果需要 Table对象，可以从表名获取
//        Table sensorTable = tableEnv.from("inputTable");

        Table resultTable = tableEnv
//                .sqlQuery("select * from " + sensorTable + " where id = 'sensor_1'"); // 操作未注册的表，不建议
                .sqlQuery("select * from inputTable where id = 'sensor_1'"); // 操作已注册的表，建议


        // 4.将 结果表 转成 流
        DataStream<Row> resultDS = tableEnv.toAppendStream(resultTable, Row.class);

        resultDS.print();

        env.execute();
    }
}
